<?php

namespace Muyuxuanpay\wechat\account;

use Muyuxuanpay\http\Http;
use Muyuxuanpay\wechat\WeChat;

class OfficialAccount extends WeChat
{
    /**
     * 公招获取code
     * @param string $redirect_uri 回调地址
     * @param string $scope 授权类型
     * @param array $parameter 其他参数
     * @return false|void
     */
    public function getCode(string $redirect_uri='',string $scope='snsapi_base',array $parameter=[]){
        $res = $this->verify([
            'app_id',
            'secret',
        ]);
        if($res===false){
            return false;
        }
        if(!empty($parameter)){
            $parameter = json_encode($parameter,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        }else{
            $parameter = "{}";
        }
        $redirect_uri = urlencode($redirect_uri);
        $parameter = urlencode($parameter);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->config['app_id']}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$parameter}#wechat_redirect";
        header("Location:".$url);
    }

    /**
     * 获取用户信息
     * @param string $code 用户code
     * @return array|false|mixed|string|null
     */
    public function getUserInfo(string $code){
        $res = $this->verify([
            'app_id',
            'secret',
        ]);
        if($res===false){
            return false;
        }
        $url = $this->domain."/sns/oauth2/access_token?appid={$this->config['app_id']}&secret={$this->config['secret']}&code={$code}&grant_type=authorization_code";
        $this->result = Http::post($url);
        return $this->getResult();
    }

}